package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"golang.org/x/crypto/bcrypt"
	"math/rand"
	"project/jwt-prac/models"
	"time"
)

func init() {
	rand.Seed(time.Now().Unix())
}

func RegisterGet(c *gin.Context) {

}

//POST;path：/register
func RegisterPost(c *gin.Context) {
	var (
		userRegister models.UserRegister
		err          error
		user         models.User
	)
	//对用户提交的注册信息进行校验
	if err = c.MustBindWith(&userRegister, binding.Form); err != nil {
		c.JSON(400, gin.H{
			"msg":   "注册信息不符合规范",
			"error": err.Error(),
		})
		c.Abort()
		return
	}
	//根据数据库对注册信息校验
	code, err := models.CheckUserRegister(userRegister)
	if err != nil {
		c.JSON(code, err.Error())
		c.Abort()
		return
	}
	//生成密码加密盐值,并生成用户信息
	PasswdHash, _ := bcrypt.GenerateFromPassword([]byte(userRegister.Password), bcrypt.DefaultCost)
	user.Email = userRegister.Email
	user.Username = userRegister.Username
	user.PasswordHash = string(PasswdHash)
	user.LoginTime = time.Now()
	user.LoginIp = c.ClientIP()
	//将用户信息入库
	code, err = models.CreateUserDB(&user)
	if err != nil {
		c.JSON(code, err.Error())
		c.Abort()
		return
	}
	//回显
	c.String(200, "register success")
}
